﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Network;

public class VisualMoveComponent : VisualComponent
{
    VisualEntity vEntity;
    Animator animator;

    public void DoUpdate(float deltaTime)
    {
        
    }

    public void Init(VisualEntity VEntity)
    {
        vEntity = VEntity;
        vEntity.RegistMsg(OpCode.move_move, VisualMove);

        animator = vEntity.GetComponent<Animator>();
    }

    public void VisualMove(byte[] msg)
    {
        move_move proto = ProtoUtil.DeserializeProto<move_move>(msg);
        Vector3 dest = new Vector3(proto.pos.x, proto.pos.y, proto.pos.z);
        Vector3 dir = dest - vEntity.transform.position; dir.y = 0;
        vEntity.transform.position = dest;
        if(dir.sqrMagnitude > 0)
        {
            vEntity.transform.forward = dir.normalized;
            animator.SetBool("IsMove", true);
        }
        else
        {
            animator.SetBool("IsMove", false);
        }
    }

    public void OnDestroy()
    {
        vEntity.UnregistMsg(OpCode.move_move);
    }

    public void GetSyncMessage(sync_state_content message)
    {
        message.move = new move_component();
        message.move.pos = new vector3();
        Vector3 pos = vEntity.transform.position;
        message.move.pos.x = pos.x;
        message.move.pos.y = pos.y;
        message.move.pos.z = pos.z;
    }

    public void RestoreState(sync_state_content message)
    {
        move_component move = message.move;
        Vector3 pos = new Vector3(move.pos.x, move.pos.y, move.pos.z);
        vEntity.transform.position = pos;
    }
}
